/**
 * Copyright (C), 2015-2018, 北京译泰教育科技有限公司
 * FileName: ControllerHelper
 * Author:   andy
 * Date:     18/1/28 下午1:10
 * Description: ${DESCRIPTION}
 * History:
 */
package org.smart4j.framework.helper;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.smart4j.framework.annotation.Action;
import org.smart4j.framework.bean.Handler;
import org.smart4j.framework.bean.Request;
import org.smart4j.framework.util.ArrayUtil;

/**
 * 控制器助手类<br>
 *
 * @author andy
 * @version V1.0
 * @date 18/1/28 下午1:10
 */
public final class ControllerHelper {

    /**
     * 用于存放请求与处理器的映射关系
     */
    private static final Map<Request, Handler> ACTION_MAP = new HashMap<>();

    static {
        // 所有的controller类
        Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
        if (CollectionUtils.isNotEmpty(controllerClassSet)) {
            for (Class<?> controllerClass : controllerClassSet) {
                // 获取controller中定义的方法
                Method[] methods = controllerClass.getDeclaredMethods();
                if (ArrayUtil.isNotEmpty(methods)){
                    // 遍历方法
                    for (Method method:methods) {
                        if (method.isAnnotationPresent(Action.class)){
                            String mapping = method.getAnnotation(Action.class).value();
                            // 验证url映射规则
                            if (mapping.matches("\\w+:/\\w*")){
                                String[] array = mapping.split(":");
                                if (ArrayUtil.isNotEmpty(array) && array.length == 2){
                                    Request request = new Request(array[0], array[1]);
                                    Handler handler = new Handler(controllerClass, method);

                                    //初始化action map
                                    ACTION_MAP.put(request, handler);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取handler
     */
    public static Handler getHandler(String requestMethod, String requestPath){
        Request request = new Request(requestMethod, requestPath);
        return ACTION_MAP.get(request);
    }

}